package com.tianji.learning.utils;

import lombok.Data;

import java.io.Serializable;
import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

@Data
public class DelayTask<T> implements Delayed, Serializable {

    private Long deadLineNanos;

    private T data;

    public static <T> DelayTask<T> of(final Duration duration, final T data) {
        return new DelayTask(data, duration);
    }

    public DelayTask(T data, Duration duration) {
        this.data = data;
        this.deadLineNanos = System.nanoTime() + duration.toNanos();
    }

    /**
     * 1、用来获取队列中每个任务 距离当前时间还有多久被执行的时间
     *
     * @param unit the time unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(Math.max(deadLineNanos - System.nanoTime(), 0), TimeUnit.NANOSECONDS);
    }

    /**
     * 2、对延时任务队列中的任务进行排序(排序依据:根据getDelay方法获取的任务延时时间进行排序，值越小，优先级越高
     *
     * @param o the object to be compared.
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        long diff = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        return diff > 0 ? 1 : diff == 0 ? 0 : -1;
    }
}
